﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;

namespace WebAPI.Utils
{
    public class Client
    {
        private string host = "localhost";

        private IDictionary<string, string> headers;

        private String contentType;

        private byte[] form = null;

        public void Header(IDictionary<string, string> headers)
        {
            this.headers = headers;
        }

        public void ContentType(String contentType)
        {
            this.contentType = contentType;
        }

        /// <summary>
        /// GET请求
        /// </summary>
        /// <param name="url">请求URL</param>
        /// <param name="querys">请求参数</param>
        /// <param name="contentType">默认JSON</param>
        /// <returns></returns>
        public string Get(string url, string querys = "", string contentType = "application/json; charset=UTF-8")
        {
            return HttpRequest(url, querys, "", "GET", contentType);
        }

        /// <summary>
        /// POST请求
        /// </summary>
        /// <param name="url">请求URL</param>
        /// <param name="bodys">JSON字符串</param>
        /// <param name="contentType">默认JSON</param>
        /// <returns></returns>
        public string Post(string url, string bodys = "", string contentType = "application/json; charset=UTF-8")
        {
            return HttpRequest(url, "", bodys, "POST", contentType);
        }

        /// <summary>
        /// PUT请求
        /// </summary>
        /// <param name="url">请求URL</param>
        /// <param name="bodys">JSON字符串</param>
        /// <param name="contentType">默认JSON</param>
        /// <returns></returns>
        public string Put(string url, string bodys)
        {
            return HttpRequest(url, "", bodys, "PUT");
        }

        /// <summary>
        /// DELETE请求
        /// </summary>
        /// <param name="url">请求URL</param>
        /// <param name="bodys">JSON字符串</param>
        /// <returns></returns>
        public string Delete(string url, string bodys = "")
        {
            return HttpRequest(url, "", bodys, "DELETE");
        }

        /// <summary>
        /// PATCH请求
        /// </summary>
        /// <param name="url">请求URL</param>
        /// <param name="bodys">JSON字符串</param>
        /// <returns></returns>
        public string Patch(string url, string bodys = "")
        {
            return HttpRequest(url, "", bodys, "PATCH");
        }

        /// <summary>
        /// POST表单数据   
        /// </summary>
        /// <param name="parameters"></param>
        public void Form(IDictionary<string, string> parameters = null)
        {
            if (!(parameters == null || parameters.Count == 0))
            {
                StringBuilder buffer = new();
                int i = 0;
                foreach (string key in parameters.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, parameters[key]);
                    }
                    i++;
                }
                byte[] data = Encoding.Default.GetBytes(buffer.ToString());
                form = data;
            }
        }

        public string HttpRequest(string url, string querys, string bodys, string method, string contentType = "application/json; charset=UTF-8")
        {
            HttpWebRequest httpRequest = null;
            HttpWebResponse httpResponse = null;

            if (0 < querys.Length)
            {
                url = url + "?" + querys;
            }

            if (host.Contains("https://"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
            }
            else
            {
                httpRequest = (HttpWebRequest)WebRequest.Create(url);
            }
            httpRequest.Method = method;
            // 请求头
            if (!(headers == null || headers.Count == 0))
            {
                foreach (string key in headers.Keys)
                {
                    httpRequest.Headers.Add(key, headers[key]);
                }
            }
            httpRequest.ContentType = contentType;
            if (0 < bodys.Length)
            {
                byte[] data = Encoding.UTF8.GetBytes(bodys);
                using (Stream stream = httpRequest.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            // 表单提交
            if (contentType == "application/x-www-form-urlencoded")
            {
                using (Stream stream = httpRequest.GetRequestStream())
                {
                    stream.Write(form, 0, form.Length);
                }
            }

            try
            {
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            }
            catch (WebException ex)
            {
                httpResponse = (HttpWebResponse)ex.Response;
            }

            //httpResponse.StatusCode
            //httpResponse.Method
            //httpResponse.Headers
            // httpResponse.GetResponseHeader("X-Ca-Error-Message")
            if (httpResponse.StatusCode != HttpStatusCode.OK)
            {
                Stream st = httpResponse.GetResponseStream();
                StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
                return reader.ReadToEnd();
            }
            else
            {
                Stream st = httpResponse.GetResponseStream();
                StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
                return reader.ReadToEnd();
            }
        }

        public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }

        // 接收GET
        public void Get()
        {
            //return Request.QueryString;
        }

        // 接收POST FORM
        public void Post()
        {
            //return Request.Form;
            //return HttpContext.Current.Request;
        }

        public void Param(HttpListenerContext context)
        {
            var body = new StreamReader(context.Request.InputStream).ReadToEnd();

            NameValueCollection coll = HttpUtility.ParseQueryString(body);

            var response = new StringBuilder();
            foreach (var key in coll.AllKeys)
            {
                response.Append(string.Format(@"form[""{0}""] = {1}\r\n", key, coll[key]));  //Edit the format string to taste
            }
            Debug.Write(response.ToString());
        }
    }
}
